<template>
  <div class="app-container">
    <el-form>
      <el-row style="padding-bottom: 10px">
        <el-col :span="12">
          <el-dropdown
            size="medium"
            trigger="click"
            @command="selectProject"
          >
            <el-button type="primary" size="medium" style="width: 200px">
              {{ projectConfig.projectName }}<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown" style="width: 180px">
              <el-dropdown-item
                v-for="item in projectData"
                :key="item.itemId"
                :command="item.itemId"
                :class="projectConfig.projectId==item.itemId?'select-item-selected':''"
              >{{ item.itemName }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-switch
            v-model="groupEditable"
            active-text="分组编辑模式"
            inactive-color="red"
            style="margin-left: 20px"
          />
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-button type="primary" size="medium" @click="popNewProject">创建项目</el-button>
          <el-button type="primary" size="medium" @click="popEditProject">编辑项目</el-button>
          <el-button type="primary" size="medium" @click="delProject">删除项目</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-tree
            ref="groupTree"
            :data="groupTree"
            node-key="id"
            default-expand-all
            :props="defaultProps"
            :expand-on-click-node="false"
            :highlight-current="true"
            @node-click="selectGroup"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span>
                <span v-if="groupEditable">
                  <el-button
                    type="text"
                    size="mini"
                    style="margin-left: 0px;"
                    @click="appendSubGroup(node, data)"
                  >创建子组</el-button>
                  <el-button
                    v-if="data.id!=0"
                    type="text"
                    size="mini"
                    style="margin-left: 0px;"
                    @click="editGroup(node, data)"
                  >编辑</el-button>
                  <el-button
                    v-if="data.id!=0"
                    type="text"
                    size="mini"
                    style="margin-left: 0px;"
                    @click="removeGroup(node, data)"
                  >删除</el-button>
                </span>
                <el-button
                  v-if="data.id!=0"
                  type="text"
                  size="mini"
                  style="margin-left: 0px;"
                  @click="popNewApiHttp(node, data)"
                >创建接口</el-button>
              </span>
            </span>
          </el-tree>
        </el-col>
        <el-col :span="18">
          <el-table ref="singleTable" :data="apiTableData" style="width: 100%">
            <el-table-column label="接口名称" prop="apiName" min-width="20%">
              <template slot-scope="scope">
                <span>{{ scope.row.apiName }}</span>
                <el-button
                  icon="el-icon-caret-right"
                  style="color: green; border: 0; padding: 0; font-size: 18px"
                  @click="run(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="接口url" prop="url" min-width="40%">
              <template slot-scope="scope">
                <span>{{ scope.row.url }}</span>
              </template>
            </el-table-column>
            <el-table-column label="请求类型" prop="dataTypeDesc" min-width="25%">
              <template slot-scope="scope">
                <span>{{ scope.row.dataTypeDesc }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="15%">
              <template slot-scope="scope">
                <el-button type="text" size="medium" @click="popEditApiHttp(scope.row)">编辑</el-button>
                <el-button
                  type="text"
                  size="medium"
                  style="margin-left: 0px"
                  @click="popCopyApiHttp(scope.row)"
                >复制</el-button>
                <el-button
                  type="text"
                  size="medium"
                  style="margin-left: 0px"
                  @click="popMoveApiHttp(scope.row)"
                >移动</el-button>
                <el-popconfirm title="确定要删除这个接口吗？" @onConfirm="delApiHttp(scope.row)">
                  <el-button slot="reference" type="text" size="medium">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog :title="projectDialogTitle" :visible.sync="projectDialogVisible" width="500px">
      <el-form>
        <el-form-item label="项目名称" label-width="100px">
          <el-input
            v-model="projectConfig.saveProjectName"
            placeholder="xx项目"
            clearable
            style="width: 300px"
            maxlength="16"
          />
        </el-form-item>
        <el-form-item label="项目权限" label-width="100px">
          <el-radio
            v-model="projectConfig.saveProjectScope"
            label="1"
            :disabled="projectConfig.projectScopeDisable"
          >公共的</el-radio>
          <el-radio
            v-model="projectConfig.saveProjectScope"
            label="2"
            :disabled="projectConfig.projectScopeDisable"
          >私有的</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="projectDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveProject()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="groupDialogTitle" :visible.sync="groupDialogVisible" width="500px">
      <el-form>
        <el-form-item label="分组名称" label-width="100px">
          <el-input
            v-model="groupConfig.groupName"
            placeholder="xx分组"
            clearable
            style="width: 300px"
            maxlength="12"
          />
        </el-form-item>
        <el-form-item label="父分组" label-width="100px">
          <el-cascader
            :key="groupConfig.refresh"
            v-model="groupConfig.parent"
            :options="groupTree"
            :props="groupCascaderConfig"
            style="width: 300px"
            @change="selectParentGroup"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="groupDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveGroup()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="httpDialogTitle" :visible.sync="httpDialogVisible" width="1000px">
      <el-form>
        <el-form-item label="接口名称" label-width="100px">
          <el-input
            v-model="httpConfig.apiName"
            placeholder="xx接口"
            clearable
            style="width: 500px"
            maxlength="12"
          />
          <el-select v-model="httpConfigEnvId" filterable clearable placeholder="请选择环境">
            <el-option
              v-for="item in envData"
              :key="item.itemId"
              :label="item.itemName"
              :value="item.itemId"
            />
          </el-select>
          <el-button type="success" @click="testApiHttp">运行测试</el-button>
        </el-form-item>
        <el-form-item label="接口地址" label-width="100px">
          <el-select v-model="httpConfig.method" placeholder="请求方法" style="width: 100px">
            <el-option label="GET" value="1" />
            <el-option label="POST" value="2" />
            <el-option label="PUT" value="3" />
            <el-option label="PATCH" value="4" />
            <el-option label="DELETE" value="5" />
          </el-select>
          <el-select v-model="httpConfig.protocol" placeholder="协议" style="width: 90px">
            <el-option label="Http" value="1" />
            <el-option label="Https" value="2" />
          </el-select>://
          <el-input
            v-model="httpConfig.apiUrl"
            placeholder="接口url"
            clearable
            style="width: 590px"
            maxlength="128"
          />
        </el-form-item>
        <el-form-item label="接口参数" label-width="100px">
          <el-tabs v-model="httpConfig.requestTab" type="card" style="width: 800px">
            <el-tab-pane label="请求头" name="1">
              <el-table
                ref="headTable"
                :data="httpConfig.headData"
                :show-header="false"
                style="width: 100%"
                :max-height="200"
              >
                <el-table-column prop="paramKey" min-width="100%">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.paramKey"
                      size="mini"
                      placeholder="参数Key"
                      @input="headInput(scope.row.paramKey, scope)"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="paramValue" min-width="100%">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.paramValue"
                      size="mini"
                      placeholder="参数Value"
                      @input="headInput(scope.row.paramValue, scope)"
                    />
                  </template>
                </el-table-column>
                <el-table-column>
                  <template slot-scope="scope">
                    <el-button
                      v-if="httpConfig.headData.length > 1 && httpConfig.headData.length !== scope.$index + 1"
                      size="mini"
                      icon="el-icon-close"
                      circle
                      @click="delHead(scope)"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="请求参数" name="2">
              <el-radio v-model="httpConfig.paramType" label="1">params</el-radio>
              <el-radio v-model="httpConfig.paramType" label="21">x-www-form-urlencoded</el-radio>
              <el-radio v-model="httpConfig.paramType" label="22">application/json</el-radio>
              <el-radio v-model="httpConfig.paramType" label="31">text/plain</el-radio>
              <el-radio v-model="httpConfig.paramType" label="4">form-data</el-radio>
              <el-table
                v-if="['1','21','4'].includes(httpConfig.paramType)"
                ref="paramTable"
                :data="httpConfig.paramData"
                :show-header="false"
                style="width: 100%"
                :max-height="200"
              >
                <el-table-column prop="paramKey" min-width="100%">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.paramKey"
                      size="mini"
                      placeholder="参数Key"
                      @input="paramInput(scope.row.paramKey, scope)"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="paramValue" min-width="100%">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.paramValue"
                      size="mini"
                      placeholder="参数Value"
                      @input="paramInput(scope.row.paramValue, scope)"
                    />
                  </template>
                </el-table-column>
                <el-table-column>
                  <template slot-scope="scope">
                    <el-button
                      v-if="httpConfig.paramData.length > 1 && httpConfig.paramData.length !== scope.$index + 1"
                      size="mini"
                      icon="el-icon-close"
                      circle
                      @click="delParam(scope)"
                    />
                  </template>
                </el-table-column>
              </el-table>
              <el-input
                v-if="['22','31'].includes(httpConfig.paramType)"
                v-model="httpConfig.bodyData"
                type="textarea"
                :autosize="{ minRows: 5, maxRows: 12}"
                style="width: 100%"
              />
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="httpDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveApiHttp">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="复制接口" :visible.sync="apiCopyDialogVisible" width="500px">
      <el-form>
        <el-form-item label="新接口名称" label-width="100px">
          <el-input
            v-model="copyHttpConfig.apiName"
            placeholder="xx接口"
            clearable
            style="width: 300px"
            maxlength="12"
          />
        </el-form-item>
        <el-form-item label="复制至分组" label-width="100px">
          <el-cascader
            :key="groupConfig.refresh"
            v-model="groupConfig.parent"
            :options="groupTree"
            :props="groupCascaderConfig"
            style="width: 300px"
            @change="selectParentGroup"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="apiCopyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="copyApi()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="移动接口" :visible.sync="apiMoveDialogVisible" width="500px">
      <el-form>
        <el-form-item label="移动至分组" label-width="100px">
          <el-cascader
            :key="groupConfig.refresh"
            v-model="groupConfig.parent"
            :options="groupTree"
            :props="groupCascaderConfig"
            style="width: 300px"
            @change="selectParentGroup"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="apiMoveDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="moveApi()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="运行结果" :visible.sync="apiRunDialogVisible" width="1024px">
      <div
        v-if="apiRunData.loading"
        v-loading="true"
        style="width: 100%; height: 400px"
        element-loading-text="请求中..."
      />
      <div v-else>
        <el-row>
          <el-col :span="16">
            <span class="text-label" style="font-weight: 700;">URL:</span>
            <span class="text-label">{{ apiRunData.requestUrl }}</span>
          </el-col>
          <el-col :span="8" style="text-align: right">
            <span class="text-label" style="font-weight: 700;">当前环境: {{ apiRunDataEnvName }}</span>
            <el-dropdown
              split-button
              type="success"
              size="small"
              class="el-dropdown-send"
              @command="selectEnv"
              @click="runCall"
            >
              发送
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  :key="''"
                  :command="''"
                  :class="apiRunDataEnvId===null?'select-item-selected':''"
                >无环境</el-dropdown-item>
                <el-dropdown-item
                  v-for="item in envData"
                  :key="item.itemId"
                  :command="item.itemId"
                  :class="apiRunDataEnvId==item.itemId?'select-item-selected':''"
                >{{ item.itemName }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <span class="text-label" style="font-weight: 700;">Status:</span>
            <span
              class="text-label"
              :style="apiRunData.success?'color: green':'color: red'"
            >{{ apiRunData.httpStatus }}</span>
          </el-col>
          <el-col :span="8">
            <span class="text-label" style="font-weight: 700;">Time:</span>
            <span
              class="text-label"
              :style="apiRunData.time<1000?'color: green':'color: red'"
            >{{ apiRunData.time }}ms</span>
          </el-col>
          <el-col :span="8">
            <span class="text-label" style="font-weight: 700;">Size:</span>
            <span class="text-label" style="color: green">{{ apiRunData.size }}B</span>
          </el-col>
        </el-row>
        <el-row>
          <el-tabs v-model="apiRunTabActive">
            <el-tab-pane label="请求" name="request">
              <div style="min-height: 200px; max-height: 300px; overflow-y: auto">
                <div style="font-weight: 500; padding-bottom: 8px;">{{ apiRunData.method }}</div>
                <el-card class="box-card" style="margin-top: 5px">
                  <div slot="header" class="clearfix">
                    <span style="font-weight: 500">请求数据:</span>
                  </div>
                  <div v-if="apiRunData.queryParam !== null && apiRunData.queryParam !== ''">
                    <span class="text-item" style="font-weight: 700;">Query Param:</span>
                    <span class="text-item">{{ apiRunData.queryParam }}</span>
                  </div>
                  <div v-for="(item, index) in apiRunData.pairParam" :key="index">
                    <span class="text-item" style="font-weight: 700;">{{ item.itemCode }}:</span>
                    <span class="text-item">{{ item.itemName }}</span>
                  </div>
                  <div v-if="apiRunData.bodyParam !== null && apiRunData.bodyParam !== ''">
                    <span class="text-item" style="font-weight: 700;">Request Payload:</span>
                    <el-input
                      v-model="apiRunData.bodyParam"
                      type="textarea"
                      :autosize="{ minRows: 1, maxRows: 1000}"
                      readonly="readonly"
                      style="width: 100%"
                    />
                  </div>
                </el-card>
                <el-card class="box-card">
                  <div slot="header" class="clearfix">
                    <div style="font-weight: 500">请求头:</div>
                  </div>
                  <div v-for="(item, index) in apiRunData.requestHeaders" :key="index">
                    <span class="text-item" style="font-weight: 700;">{{ item.itemCode }}:</span>
                    <span class="text-item">{{ item.itemName }}</span>
                  </div>
                </el-card>
              </div>
            </el-tab-pane>
            <el-tab-pane label="响应" name="response">
              <div style="min-height: 200px; max-height: 300px; overflow-y: auto">
                <el-card class="box-card" style="margin-top: 5px">
                  <div slot="header" class="clearfix">
                    <span style="font-weight: 500">响应数据:</span>
                  </div>
                  <div
                    v-if="apiRunData.responseContent !== null && apiRunData.responseContent !== ''"
                  >
                    <el-input
                      v-model="apiRunData.responseContent"
                      type="textarea"
                      :autosize="{ minRows: 1, maxRows: 1000}"
                      readonly="readonly"
                      style="width: 100%"
                    />
                  </div>
                </el-card>
                <el-card class="box-card">
                  <div slot="header" class="clearfix">
                    <div style="font-weight: 500">响应头:</div>
                  </div>
                  <div v-for="(item, index) in apiRunData.responseHeaders" :key="index">
                    <span class="text-item" style="font-weight: 700;">{{ item.itemCode }}:</span>
                    <span class="text-item" style>{{ item.itemName }}</span>
                  </div>
                </el-card>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="apiRunDialogVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { requestProjectApi } from '@/api/project/project'
import { requestCommonApi } from '@/api/common/common'
import { requestApiHttpApi } from '@/api/api/apiHttp'

export default {
  data() {
    return {
      projectData: [],
      projectConfig: {
        projectName: '请选择项目',
        projectId: null,
        projectScope: null,
        projectScopeDisable: false,
        saveProjectName: null,
        saveProjectId: null,
        saveProjectScope: '1'
      },
      projectDialogVisible: false,
      projectDialogTitle: null,
      groupEditable: false,
      groupTree: [],
      defaultProps: {
        children: 'children',
        label: 'groupName'
      },
      groupDialogVisible: false,
      groupDialogTitle: null,
      groupConfig: {
        refresh: 1,
        groupId: null,
        groupName: null,
        parent: []
      },
      groupCascaderConfig: {
        expandTrigger: 'hover',
        checkStrictly: true,
        children: 'children',
        value: 'id',
        label: 'groupName'
      },
      apiTableData: [],
      httpDialogVisible: false,
      httpDialogTitle: null,
      httpConfigEnvId: '',
      httpConfig: {
        id: null,
        requestTab: '2',
        groupId: null,
        apiName: null,
        apiUrl: null,
        method: '1',
        protocol: '1',
        paramType: '1',
        headData: [{
          paramKey: '',
          paramValue: ''
        }],
        paramData: [{
          paramKey: '',
          paramValue: ''
        }],
        bodyData: null
      },
      apiCopyDialogVisible: false,
      copyHttpConfig: {
        id: null,
        apiName: null,
        groupId: null
      },
      apiMoveDialogVisible: false,
      moveHttpConfig: {
        id: null,
        groupId: null
      },
      apiRunDialogVisible: false,
      apiRunTabActive: 'response',
      apiRunDataEnvId: null,
      apiRunDataEnvName: '无环境',
      apiRunData: {
        loading: true,
        apiId: null,
        requestUrl: null,
        success: false,
        httpStatus: null,
        time: null,
        size: null,
        method: null,
        requestHeaders: null,
        queryParam: null,
        pairParam: null,
        bodyParam: null,
        responseHeaders: null,
        responseContent: null
      },
      envData: []
    }
  },
  computed: {
    groupConfigParent() {
      return this.groupConfig.parent
    }
  },
  watch: {
    groupConfigParent() {
      ++this.groupConfig.refresh
    },
    groupTree() {
      ++this.groupConfig.refresh
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      requestProjectApi('userProjectDropDown', {}).then(response => {
        // console.log(response.data)
        if (response.data === null || response.data.dataList === null || response.data.dataList.length === 0) {
          this.projectConfig.projectName = '请先创建项目'
          return
        }
        response.data.dataList.forEach(item => {
          this.projectData.push({
            itemId: item.itemId,
            itemCode: item.itemCode,
            itemName: item.itemName
          })
        })
      })
      requestCommonApi('envDropDownList', {}).then(response => {
        response.data.dataList.forEach(item => {
          this.envData.push({
            itemId: item.itemId,
            itemName: item.itemName
          })
        })
      })
    },
    selectProject(projectId) {
      this.projectData.forEach(item => {
        if (item.itemId === projectId) {
          this.projectConfig.projectName = item.itemName
          this.projectConfig.projectId = item.itemId
          this.projectConfig.projectScope = item.itemCode
          this.groupTree = []
          this.apiTableData = []
          this.refreshGroupTree()
        }
      })
    },
    refreshGroupTree() {
      const param = {
        id: this.projectConfig.projectId
      }
      requestProjectApi('groupTree', param).then(response => {
        if (response.code === '200') {
          this.groupTree = response.data.nodeList
        }
      })
    },
    popNewProject() {
      this.projectDialogTitle = '创建项目'
      this.projectDialogVisible = true
      this.projectConfig.projectScopeDisable = false
      this.projectConfig.saveProjectName = null
      this.projectConfig.saveProjectId = null
      this.projectConfig.saveProjectScope = '1'
    },
    popEditProject() {
      this.projectDialogTitle = '编辑项目'
      if (this.projectConfig.projectId === null) {
        this.$message.error('请先选择一个项目')
        return
      }
      this.projectDialogVisible = true
      this.projectConfig.saveProjectName = this.projectConfig.projectName
      this.projectConfig.saveProjectId = this.projectConfig.projectId
      this.projectConfig.saveProjectScope = this.projectConfig.projectScope
      if (this.projectConfig.saveProjectScope === '1') {
        this.projectConfig.projectScopeDisable = true
      } else {
        this.projectConfig.projectScopeDisable = false
      }
    },
    saveProject() {
      const param = {
        id: this.projectConfig.saveProjectId,
        projectName: this.projectConfig.saveProjectName,
        projectScope: this.projectConfig.saveProjectScope
      }
      requestProjectApi('saveProject', param).then(response => {
        if (response.code === '200') {
          if (this.projectConfig.saveProjectId == null) {
            this.projectData.push({
              itemId: response.data.id,
              itemCode: this.projectConfig.saveProjectScope,
              itemName: this.projectConfig.saveProjectName
            })
            this.projectConfig.projectId = response.data.id
            this.groupTree = []
          } else {
            this.projectData.forEach(item => {
              if (item.itemId === this.projectConfig.saveProjectId) {
                item.itemName = this.projectConfig.saveProjectName
                item.itemCode = this.projectConfig.saveProjectScope
              }
            })
          }
          this.projectConfig.projectName = this.projectConfig.saveProjectName
          this.projectConfig.projectScope = this.projectConfig.saveProjectScope
          this.refreshGroupTree()
          this.projectDialogVisible = false
        } else {
          this.$message.error(response.message)
        }
      })
    },
    delProject() {
      if (this.projectConfig.projectId === null) {
        this.$message.error('请先选择一个项目')
        return
      }
      let projectName
      let projectIndex
      this.projectData.forEach((item, index) => {
        if (this.projectConfig.projectId === item.itemId) {
          projectIndex = index
          projectName = item.itemName
        }
      })
      this.$confirm('确定删除"' + projectName + '"项目吗？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const param = {
          id: this.projectConfig.projectId
        }
        requestProjectApi('delProject', param).then(response => {
          if (response.code === '200') {
            // console.log(projectIndex)
            this.projectData.splice(projectIndex, 1)
            if (this.projectData.length === 0) {
              this.projectConfig.projectName = '请先创建项目'
            } else {
              this.projectConfig.projectName = '请选择项目'
            }
            this.projectConfig.projectId = null
            this.groupTree = []
          } else {
            this.$message.error(response.message)
          }
        })
      }).catch(() => {
      })
    },
    selectParentGroup(value) {
      // console.log(this.groupConfig.parent)
    },
    appendSubGroup(node, data) {
      const parentPath = []
      do {
        parentPath.unshift(node.data.id)
        node = node.parent
      } while (node.key != null)
      // console.log(parentPath)
      this.groupConfig.parent = parentPath
      this.groupConfig.groupId = null
      this.groupConfig.groupName = null

      this.groupDialogTitle = '创建分组'
      this.groupDialogVisible = true
    },
    editGroup(node, data) {
      node = node.parent
      const parentPath = []
      do {
        parentPath.unshift(node.data.id)
        node = node.parent
      } while (node.key != null)
      // console.log(parentPath)
      this.groupConfig.parent = parentPath
      this.groupConfig.groupId = data.id
      this.groupConfig.groupName = data.groupName

      this.groupDialogTitle = '编辑分组'
      this.groupDialogVisible = true
    },
    removeGroup(node, data) {
      this.$confirm('确定删除"' + data.groupName + '"分组及其所有子分组吗？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const param = {
          id: data.id
        }
        requestProjectApi('delGroup', param).then(response => {
          if (response.code === '200') {
            this.refreshGroupTree()
          } else {
            this.$message.error(response.message)
          }
        })
      }).catch(() => {
      })
    },
    saveGroup() {
      const param = {
        id: this.groupConfig.groupId,
        projectId: this.projectConfig.projectId,
        groupName: this.groupConfig.groupName,
        parentId: this.groupConfig.parent[this.groupConfig.parent.length - 1]
      }
      requestProjectApi('saveGroup', param).then(response => {
        if (response.code === '200') {
          this.refreshGroupTree()
          this.groupDialogVisible = false
        } else {
          this.$message.error(response.message)
        }
      })
    },
    selectGroup(data) {
      this.listByGroup(data.id)
    },
    listByGroup(groupId) {
      this.apiTableData = []
      const param = {
        id: groupId
      }
      requestApiHttpApi('listByGroup', param).then(response => {
        if (response.code === '200') {
          response.data.apiList.forEach(data => {
            this.apiTableData.push({
              id: data.id,
              groupId: data.groupId,
              apiName: data.apiName,
              url: data.url,
              dataTypeDesc: data.dataTypeDesc
            })
          })
        } else {
          this.$message.error(response.message)
        }
      })
    },
    popNewApiHttp(node, data) {
      this.httpDialogVisible = true
      this.httpDialogTitle = '创建接口'
      this.httpConfig = {
        id: null,
        requestTab: '2',
        groupId: data.id,
        apiName: null,
        apiUrl: null,
        method: '1',
        protocol: '1',
        paramType: '1',
        headData: [{
          paramKey: '',
          paramValue: ''
        }],
        paramData: [{
          paramKey: '',
          paramValue: ''
        }],
        bodyData: null
      }
    },
    popEditApiHttp(row) {
      const param = {
        id: row.id
      }
      requestApiHttpApi('detail', param).then(response => {
        if (response.code === '200') {
          const data = response.data
          this.httpConfig = {
            id: data.id,
            requestTab: '2',
            groupId: data.groupId,
            apiName: data.apiName,
            apiUrl: data.apiUrl,
            method: data.method + '',
            protocol: data.protocol + '',
            paramType: data.dataType + '',
            headData: [],
            paramData: [],
            bodyData: data.requestBody
          }
          if (data.headMap != null) {
            for (const key in data.headMap) {
              this.httpConfig.headData.push({
                paramKey: key,
                paramValue: data.headMap[key]
              })
            }
          }
          this.httpConfig.headData.push({
            paramKey: '',
            paramValue: ''
          })
          if (data.paramMap != null) {
            for (const key in data.paramMap) {
              this.httpConfig.paramData.push({
                paramKey: key,
                paramValue: data.paramMap[key]
              })
            }
          }
          this.httpConfig.paramData.push({
            paramKey: '',
            paramValue: ''
          })
          this.httpDialogVisible = true
          this.httpDialogTitle = '编辑接口'
        } else {
          this.$message.error(response.message)
        }
      })
    },
    saveApiHttp() {
      const param = this.getApiConfigParam()
      // console.log(param)
      requestApiHttpApi('saveApiHttp', param).then(response => {
        if (response.code === '200') {
          this.listByGroup(this.httpConfig.groupId)
          this.httpDialogVisible = false
        } else {
          this.$message.error(response.message)
        }
      })
    },
    testApiHttp() {
      if (this.httpConfigEnvId === '') {
        this.apiRunDataEnvName = '无环境'
        this.apiRunDataEnvId = null
      } else {
        this.envData.forEach(item => {
          if (item.itemId === this.httpConfigEnvId) {
            this.apiRunDataEnvName = item.itemName
            this.apiRunDataEnvId = item.itemId
          }
        })
      }
      this.apiRunData.apiId = null
      this.apiRunDialogVisible = true
      this.runCall()
    },
    getApiConfigParam() {
      const param = {
        id: this.httpConfig.id,
        groupId: this.httpConfig.groupId,
        apiName: this.httpConfig.apiName,
        protocol: this.httpConfig.protocol,
        method: this.httpConfig.method,
        apiUrl: this.httpConfig.apiUrl,
        dataType: this.httpConfig.paramType,
        requestBody: this.httpConfig.bodyData
      }
      const headData = {}
      this.httpConfig.headData.forEach(item => {
        if (item.paramKey !== '') {
          headData[item.paramKey] = item.paramValue
        }
      })
      const paramData = {}
      this.httpConfig.paramData.forEach(item => {
        if (item.paramKey !== '') {
          paramData[item.paramKey] = item.paramValue
        }
      })
      param['headMap'] = headData
      param['paramMap'] = paramData
      return param
    },
    delApiHttp(row) {
      const param = {
        id: row.id
      }
      requestApiHttpApi('delApiHttp', param).then(response => {
        if (response.code === '200') {
          this.listByGroup(row.groupId)
        } else {
          this.$message.error(response.message)
        }
      })
    },
    paramInput(value, scope) {
      if (value !== '' && this.httpConfig.paramData.length === scope.$index + 1) {
        this.httpConfig.paramData.push({
          paramKey: '',
          paramValue: ''
        })
        const paramTable = this.$refs.paramTable
        window.setTimeout(function() {
          paramTable.bodyWrapper.scrollTop = paramTable.bodyWrapper.scrollHeight
        }, 10)
      }
    },
    delParam(scope) {
      this.httpConfig.paramData.splice(scope.$index, 1)
    },
    headInput(value, scope) {
      if (value !== '' && this.httpConfig.headData.length === scope.$index + 1) {
        this.httpConfig.headData.push({
          paramKey: '',
          paramValue: ''
        })
        const headTable = this.$refs.headTable
        window.setTimeout(function() {
          headTable.bodyWrapper.scrollTop = headTable.bodyWrapper.scrollHeight
        }, 10)
      }
    },
    delHead(scope) {
      this.httpConfig.headData.splice(scope.$index, 1)
    },
    popCopyApiHttp(row) {
      this.apiCopyDialogVisible = true
      this.copyHttpConfig.id = row.id
      this.copyHttpConfig.apiName = row.apiName + ' 的复制'
      this.copyHttpConfig.groupId = row.groupId
      let node = this.$refs.groupTree.getNode(row.groupId)
      const parentPath = []
      do {
        parentPath.unshift(node.data.id)
        node = node.parent
      } while (node.key != null)
      // console.log(parentPath)
      this.groupConfig.parent = parentPath
    },
    copyApi() {
      const groupId = this.groupConfig.parent[this.groupConfig.parent.length - 1]
      if (groupId === 0) {
        this.$message.error('不能复制至分组根目录')
        return
      }
      const param = {
        id: this.copyHttpConfig.id,
        groupId: this.groupConfig.parent[this.groupConfig.parent.length - 1],
        apiName: this.copyHttpConfig.apiName
      }
      requestApiHttpApi('copyApiHttp', param).then(response => {
        if (response.code === '200') {
          this.listByGroup(this.copyHttpConfig.groupId)
          this.apiCopyDialogVisible = false
        } else {
          this.$message.error(response.message)
        }
      })
    },
    popMoveApiHttp(row) {
      this.apiMoveDialogVisible = true
      this.moveHttpConfig.id = row.id
      this.moveHttpConfig.groupId = row.groupId
      let node = this.$refs.groupTree.getNode(row.groupId)
      const parentPath = []
      do {
        parentPath.unshift(node.data.id)
        node = node.parent
      } while (node.key != null)
      // console.log(parentPath)
      this.groupConfig.parent = parentPath
    },
    moveApi() {
      const groupId = this.groupConfig.parent[this.groupConfig.parent.length - 1]
      if (groupId === 0) {
        this.$message.error('不能移动至分组根目录')
        return
      }
      const param = {
        id: this.moveHttpConfig.id,
        groupId: this.groupConfig.parent[this.groupConfig.parent.length - 1]
      }
      requestApiHttpApi('moveApiHttp', param).then(response => {
        if (response.code === '200') {
          this.listByGroup(this.moveHttpConfig.groupId)
          this.apiMoveDialogVisible = false
        } else {
          this.$message.error(response.message)
        }
      })
    },
    run(row) {
      this.apiRunData.apiId = row.id
      this.apiRunDialogVisible = true
      this.runCall()
    },
    runCall() {
      // this.apiRunData.loading = true
      // const callTimeout = setTimeout(() => {
      //   const apiId = this.apiRunData.apiId
      //   this.apiRunData = {
      //     loading: false,
      //     apiId: apiId,
      //     requestUrl: null,
      //     success: false,
      //     httpStatus: null,
      //     time: null,
      //     size: null,
      //     method: null,
      //     requestHeaders: null,
      //     queryParam: null,
      //     pairParam: null,
      //     bodyParam: null,
      //     responseHeaders: null,
      //     responseContent: null
      //   }
      // }, 5000)
      let param = {}
      if (this.apiRunData.apiId === null) {
        param = this.getApiConfigParam()
        param.id = null
        param.envId = this.apiRunDataEnvId
      } else {
        param = {
          id: this.apiRunData.apiId,
          envId: this.apiRunDataEnvId
        }
      }
      if (param.envId === null) {
        this.apiRunData.loading = false
        return
      }
      console.log(param)
      this.apiRunData = {
        loading: true,
        apiId: this.apiRunData.apiId,
        requestUrl: null,
        success: false,
        httpStatus: null,
        time: null,
        size: null,
        method: null,
        requestHeaders: null,
        queryParam: null,
        pairParam: null,
        bodyParam: null,
        responseHeaders: null,
        responseContent: null
      }
      requestApiHttpApi('run', param).then(response => {
        console.log('run over')
        if (response.code === '200') {
          const data = response.data
          this.apiRunData.requestUrl = data.requestUrl
          this.apiRunData.success = data.success
          this.apiRunData.httpStatus = data.httpStatus
          this.apiRunData.time = data.time
          this.apiRunData.size = data.size

          this.apiRunData.method = data.method + ' ' + data.urlPath + ' ' + data.protocolVersion
          this.apiRunData.requestHeaders = data.requestHeaders
          this.apiRunData.queryParam = data.queryParam
          this.apiRunData.pairParam = data.pairParam
          this.apiRunData.bodyParam = data.bodyParam

          this.apiRunData.responseHeaders = data.responseHeaders
          this.apiRunData.responseContent = data.responseContent

          this.apiRunData.loading = false
          // clearTimeout(callTimeout)
        } else {
          this.apiRunData.loading = false
          this.$message.error(response.message)
        }
      })
    },
    selectEnv(envId) {
      if (envId === '') {
        this.apiRunDataEnvName = '无环境'
        this.apiRunDataEnvId = null
      } else {
        this.envData.forEach(item => {
          if (item.itemId === envId) {
            this.apiRunDataEnvName = item.itemName
            this.apiRunDataEnvId = item.itemId
          }
        })
      }
      this.runCall()
    }
  }
}
</script>

<style>
.el-button-group > button:first-child {
  width: 150px;
}
.el-dropdown-send > .el-button-group > button:first-child {
  width: 70px;
}
.select-item-selected {
  color: #409eff;
  font-weight: 700;
  background-color: #f5f7fa;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.text-label {
  font-size: 14px;
  color: #606266;
  line-height: 40px;
  padding: 0 12px 0 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

.text-item {
  font-size: 14px;
  color: #606266;
  line-height: 20px;
  padding: 0 12px 0 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  word-break: break-all;
}

.el-card__body {
  padding-top: 5px;
  padding-bottom: 5px;
  padding-right: 0px;
}
.el-card__header {
  padding-left: 5px;
  padding-top: 5px;
  padding-bottom: 5px;
}
</style>

